﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using APH.Parl2.Client.Publishing.WPF.PublishingManager;
using System.IO;
using System.ComponentModel;
using Microsoft.Win32;
using System.Transactions;

namespace APH.Parl2.Client.Publishing.WPF
{
    public class PublishViewModel : INotifyPropertyChanged
    {
        #region FilePath

        private string _filePath = null;

        public string FilePath
        {
            get { return _filePath; }
            protected set
            {
                if (_filePath != value)
                {
                    _filePath = value;
                    NotifyChanged("FilePath");
                }
            }
        }

        #endregion // FilePath

        public void BrowseForFile()
        {
            var ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == true)
                FilePath = ofd.FileName;
        }

        public void Publish()
        {
            IPublishingManager publishingManager = new PublishingManagerClient();

            IncomingDocumentData docData = new IncomingDocumentData();
            docData.ContentType = "Document";

            using (var fileStream = File.OpenRead(FilePath))
            using (var reader = new BinaryReader(fileStream))
            {                
                docData.DocumentBytes = reader.ReadBytes((int)fileStream.Length);
            }

            using (var ts = new TransactionScope())
            {
                publishingManager.Publish(docData);
                ts.Complete();
            }
        }

        protected void NotifyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    }
}
